import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { PrimeTable } from '../data/prime-table';

@Injectable({
  providedIn: 'root'
})

export class PrimeTableService {
  constructor(private http: HttpClient) {}

  private dataUrl = 'api/primeData';

  // 错误处理
  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      console.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    }
  }

  // 获取列表数据
  getPrimelists(): Observable<PrimeTable[]> {
    return this.http
                .get<PrimeTable[]>(this.dataUrl)
                .pipe(
                  tap(_ => console.log('fetched prime list')),
                  catchError(this.handleError<PrimeTable[]>('getGridlists', []))
                );
  }

}
